use std::sync::mpsc::Sender;
use std::thread;

pub enum SoundEffect {
    Flap,
    Hit,
    GameOver,
    Fruit,
}

pub fn start_sound_thread() -> Sender<SoundEffect> {
    use rodio::{Decoder, OutputStream, Sink};
    use std::fs::File;
    use std::io::BufReader;
    use std::sync::mpsc;

    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        // 初始化音频输出流
        let (_stream, stream_handle) = match OutputStream::try_default() {
            Ok(stream) => stream,
            Err(_) => {
                eprintln!("无法初始化音频输出，将使用控制台输出");
                // 如果音频初始化失败，回退到控制台输出
                loop {
                    if let Ok(effect) = rx.recv() {
                        match effect {
                            SoundEffect::Flap => println!("播放跳跃音效"),
                            SoundEffect::Hit => println!("播放撞击音效"),
                            SoundEffect::GameOver => println!("播放游戏结束音效"),
                            SoundEffect::Fruit => println!("播放吃水果音效"),
                        }
                    }
                }
            }
        };

        loop {
            if let Ok(effect) = rx.recv() {
                let file_path = match effect {
                    SoundEffect::Flap => "assets/flap.wav",
                    SoundEffect::Hit => "assets/hit.wav",
                    SoundEffect::GameOver => "assets/gameover.wav",
                    SoundEffect::Fruit => "assets/fruit.wav",
                };
                
                // 尝试播放音效文件
                if let Ok(file) = File::open(file_path) {
                    if let Ok(source) = Decoder::new(BufReader::new(file)) {
                        if let Ok(sink) = Sink::try_new(&stream_handle) {
                            sink.append(source);
                            sink.detach(); // 播放后自动释放
                        }
                    }
                }
            }
        }
    });

    tx
}